package com.zxk.version2.provider;



import com.zxk.version2.core.RpcRequest;
import com.zxk.version2.core.RpcResponse;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 朱小康
 */
public class RpcServer {

    public static void main(String[] args) {
        //服务端以BIO的方式监听socket

        UserServiceImpl userService = new UserServiceImpl();

        try {
            ServerSocket serverSocket = new ServerSocket(8081);
            System.out.println("服务端启动了");
            while (true){
                Socket socket = serverSocket.accept();
                new Thread(()->{
                    try {
                        InputStream inputStream = socket.getInputStream();
                        OutputStream outputStream = socket.getOutputStream();
                        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

                        //读取客户端传过来的id
                        RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
                        //查询user信息
                        Method method = userService.getClass().getMethod(rpcRequest.getMethodName(),rpcRequest.getParamsTypes());
                        Object invoke = method.invoke(userService, rpcRequest.getArgs());

                        objectOutputStream.writeObject(RpcResponse.success(invoke));

                        objectOutputStream.flush();

                    } catch (IOException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                        e.printStackTrace();
                    }


                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
